package com.example.onlinemusicserver2024.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinemusicserver2024.common.R;
import com.example.onlinemusicserver2024.mapper.CommentMapper;
import com.example.onlinemusicserver2024.model.domain.Comment;
import com.example.onlinemusicserver2024.model.request.UserSupportRequest;
import com.example.onlinemusicserver2024.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Override
    public R getComments(int songId) {
        // 设置查询条件
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_id", songId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return R.success("查询成功", comments);
    }

    @Override
    public R getCommentsBySongListId(int songListId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_list_id", songListId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return R.success("查询成功", comments);
    }

    @Override
    public R getCommentList(int songListId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_list_id", songListId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return R.success("查询成功", comments);
    }

    @Override
    public R addComment(Comment comment) {

        comment.setType(Byte.parseByte("1"));
        comment.setUp(0);
        comment.setCreateTime(new Date());
        if (commentMapper.insert(comment) > 0) {
            return R.success("评论成功");
        } else {
            return R.error("评论失败");
        }

    }

    @Override
    public R deleteCommentById(int id) {
        if (commentMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R userLike(UserSupportRequest userSupportRequest) {
        int commentId = userSupportRequest.getCommentId();
        //查询该id对应的评论
        Comment comment = commentMapper.selectById(commentId);
        int up = comment.getUp();
        comment.setUp(up + 1);
        // 更新评论记录
        int count = commentMapper.updateById(comment);
        if (count > 0) {
            return R.success("点赞成功");
        } else {
            return R.error("点赞失败");
        }
    }
}
